package com.gitee.wsl.doc.prosemirror.state.bookmark

import com.gitee.wsl.doc.prosemirror.model.node.Node
import com.gitee.wsl.doc.prosemirror.state.selection.NodeSelection
import com.gitee.wsl.doc.prosemirror.state.selection.Selection
import com.gitee.wsl.doc.prosemirror.transform.map.Mappable

class NodeBookmark(val anchor: Int) : SelectionBookmark {
    override fun map(mapping: Mappable): SelectionBookmark {
        val (deleted, pos) = mapping.mapResult(this.anchor).run { deleted to pos }
        return if (deleted) TextBookmark(pos, pos) else NodeBookmark(pos)
    }

    @Suppress("ktlint:standard:property-naming")
    override fun resolve(doc: Node): Selection {
        val _pos = doc.resolve(this.anchor)
        val node = _pos.nodeAfter
        if (node != null && NodeSelection.Companion.isSelectable(node)) return NodeSelection(_pos)
        return Selection.near(_pos)
    }
}